import { Component, OnInit } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { DatePipe } from '@angular/common';
import { ActivatedRoute } from '@angular/router';
import { Observable, Observer } from 'rxjs';
import { NzUploadFile } from 'ng-zorro-antd/upload';
import { PermissionService } from '../../../../service/permission.service';
import { CommonService } from '../../../../services-common/common.service';
import { CommidityWatermarkManageService } from '../commidity-watermark-list/commidity-watermark-manage.service';

@Component({
  selector: 'app-commidity-watermark-edit',
  templateUrl: './commidity-watermark-edit.component.html',
  styleUrls: ['./commidity-watermark-edit.component.scss'],
  providers: [DatePipe]
})
export class CommidityWatermarkEditComponent implements OnInit {

  formLabelWidth: string = '108px';
  routeParams: any = {};

  formParams: any = {
    name: '', // 标题
    status: '', // 状态
    img: '', // 水印图
    remark: '', // 备注
    useBeginTime: '', // 生效开始时间
    useEndTime: '', // 生效结束时间
    userType: '', // 适用用户

    containsModel: '', // 机型list 0：为全部 -1：为全不选
    containsSupplier: '', // 货主list 0：为全部 -1：为全不选
    containsColourB: '', // B端成色list 0：为全部 -1：为全不选
    containsColourC: '', // C端成色list 0：为全部 -1：为全不选
    filterGoods: '', // 排除商品list 0：为全部
    containsGoods: '' // 追加商品list 0：为全部
  };
  subformLoading = false;

  // 生效日期
  takeEffectDates: any = [];

  supplierOptions: any = []; // 供应商 | 货主
  supplierSelected: any = []; // 供应商 | 货主

  modelAll: boolean = false; // 机型全选
  supplierAll: boolean = false; // 货主全选

  // 成色B端 options
  conditionOptionsB: any = [];
  selectConditionB: any = [];

  // 成色C端 options
  conditionOptionsC: any = [];
  selectConditionC: any = [];

  // 选择指定机型
  isModelVisible = false;
  defaultModelKeys: any[] = [];

  // 指定商品勾选 Modal
  modalGoodsType: number = 1; // 1：排除可用 2：追加可用
  isGoodsVisible = false;
  modelGoodOptions: any = [];
  disabledOptions: any = [];

  excludeGoodsIds: any = []; // 排除可用ids
  addGoodsIds: any = []; // 追加可用ids

  // 查看已选商品 Modal
  isPreviewVisible = false;
  previewGoodIds: any = [];
  previewTable: any = [];

  /**
   * 水印冲突验证 Modal
   * ----------------------------------------------------------------
   */
  isConflictVisible = false;
  conflictLoading = false;
  conflictTableData: any[] = [];

  constructor(
    private message: NzMessageService,
    private datePipe: DatePipe,
    private commonService: CommonService,
    public permission: PermissionService,
    private activatedRoute: ActivatedRoute,
    private services: CommidityWatermarkManageService
  ) {
    activatedRoute.queryParams.subscribe((res: any) => {
      this.routeParams = res || {};
    })
  }

  ngOnInit(): void {
    if (this.routeParams.id) {
      this.loadDetailsData();
    } else {
      this.loadSupplierOptions();
      this.initconditionDatas();
    }
  }

  // 查询供应商 | 货主
  async loadSupplierOptions() {
    const data = await this.commonService.getSupplierList();
    this.supplierOptions = data.length ? data.filter((item: any) => item.name) : [];
    this.supplierOptions.unshift({
      id: 0,
      name: '自营'
    })
  }

  // 成色options
  async initconditionDatas() {
    this.conditionOptionsB = await this.commonService.getDictList('machine_condition_b');
    this.conditionOptionsC = await this.commonService.getDictList('machine_condition');
  }

  // 详情
  async loadDetailsData() {
    await this.loadSupplierOptions();
    await this.initconditionDatas();

    const msgId = this.message.loading('数据加载中..', { nzDuration: 0 }).messageId;
    const {code, data, message}: any = await this.services.queryGoodsWaterDetails({id: this.routeParams.id});
    this.message.remove(msgId);

    if (code === 0) {
      for (let key in this.formParams) {
        this.formParams[key] = !this.commonService.isEmpty(data[key]) ? data[key] : '';
      }

      this.takeEffectDates = [data.useBeginTime, data.useEndTime];

      // 指定机型
      switch (data.containsModel) {
        case '0':
          this.modelAll = true;
          break;
        case '-1':
          this.modelAll = false;
          break;
        default:
          this.modelAll = false;
          break;
      }
      this.formParams.containsModel = data.containsModel;
      let modelArr = this.commonService.isEmpty(data.containsModel) || ['0', '-1'].includes(data.containsModel) ? [] : data.containsModel.split(',');
      this.defaultModelKeys = [...modelArr];

      // 货主
      if (data.containsSupplier === '-1') {
        this.supplierAll = false;
        this.supplierSelected = [];
      } else {
        let tempSuppList = data.containsSupplier.split(',').map((m: any) => +m);
        if (tempSuppList.length === this.supplierOptions.length) {
          this.supplierAll = true;
        } else {
          this.supplierAll = false;
        }
        this.supplierSelected = tempSuppList;
      }
      
      // B端成色
      if (data.containsColourB === '0') {
        this.selectConditionB = this.conditionOptionsB.map((item: any) => item.id);
      } else if (data.containsColourB === '-1') {
        this.selectConditionB = [];
      } else {
        this.selectConditionB = data.containsColourB.split(',').map((m: any) => +m);
      }

      // C端成色
      if (data.containsColourC === '0') {
        this.selectConditionC = this.conditionOptionsC.map((item: any) => item.id);
      } else if (data.containsColourB === '-1') {
        this.selectConditionC = [];
      } else {
        this.selectConditionC = data.containsColourC.split(',').map((m: any) => +m);
      }
      
      this.formParams.filterGoods = data.filterGoods; // 排除商品
      this.excludeGoodsIds = (data.filterGoods && data.filterGoods != '0') ? data.filterGoods.split(',') : []; // 排除商品Ids
      this.formParams.containsGoods = data.containsGoods; // 追加商品
      this.addGoodsIds = (data.containsGoods && data.containsGoods != '0') ? data.containsGoods.split(',') : []; // 追加商品商品Ids
    } else {
      this.message.error(message);
    }
  }

  /**
   * ----------------------------------------------------------------
   * 指定机型 Modal Select Tree
   * ----------------------------------------------------------------
   */
  selectMoreModel() {
    this.defaultModelKeys = [];
    this.defaultModelKeys = this.mergeTreeKey();
    this.isModelVisible = true;
  }

  subModelTree(objs: any) {
    // this.formParams.containsTypes = objs.brandList.join(',');
    // this.formParams.containsSeries = objs.seriesList.join(',');
    this.formParams.containsModel = objs.modelList.join(',');
    this.defaultModelKeys = this.mergeTreeKey();
    if (this.defaultModelKeys.length) {
      this.modelAll = false;
    }
  }

  mergeTreeKey() {
    // let brandArr = this.formParams.containsTypes ? this.formParams.containsTypes.split(',') : [];
    // let seriesArr = this.formParams.containsSeries ? this.formParams.containsSeries.split(',') : [];
    let modelArr = (this.commonService.isEmpty(this.formParams.containsModel) || this.formParams.containsModel == '0' || this.formParams.containsModel == '-1') ? [] : this.formParams.containsModel.split(',');
    return modelArr.length ? [...modelArr].map((item: any) => +item) : [];
  }

  /**
   * ----------------------------------------------------------------
   * 商品选择 Modal Table
   * ----------------------------------------------------------------
   */
  showSelectGoods(type: number) {
    // type 1：排除可用 2：追加可用
    if (type === 1) {
      this.modelGoodOptions = this.excludeGoodsIds;
      this.disabledOptions = this.addGoodsIds;
    } else {
      this.modelGoodOptions = this.addGoodsIds;
      this.disabledOptions = this.excludeGoodsIds;
    }
    this.modalGoodsType = type;
    this.isGoodsVisible = true;
  }

  submitSelectGoods(obj: any) {
    // 1：排除可用 2：追加可用
    if (this.modalGoodsType === 1) {
      this.excludeGoodsIds = obj.ids;
    } else {
      this.addGoodsIds = obj.ids;
    }
  }

  /**
   * ----------------------------------------------------------------
   * 勾选预览 Modal Table
   * ----------------------------------------------------------------
   */
  previewModal(type: number) {
    if (type === 1) {
      this.previewGoodIds = this.excludeGoodsIds;
    } else {
      this.previewGoodIds = this.addGoodsIds;
    }
    this.isPreviewVisible = true;
  }

  addExcludeChange(result: Array<any>) {
    this.modelGoodOptions = [...result];
  }

  // params handle 0：为全部 -1：为全不选
  paramHandle(state: boolean, result: any) {
    let tempStr = '';
    if (state) {
      tempStr = '0';
    } else if (!state && !result.length) {
      tempStr = '-1';
    } else {
      if (Object.prototype.toString.call(result) === '[object Array]') {
        tempStr = result.join(',');
      } else {
        tempStr = result;
      }
    }
    return tempStr;
  }

  /**
   * ----------------------------------------------------------------
   * 货主 供货商
   * ----------------------------------------------------------------
   */

  /**
   * 机型 | 货主全选 Change
   * @param val 
   * @param type 1：机型 2：货主
   */
  modelOwnerAllChange(val: any, type: number) {
    switch (type) {
      case 1:
        this.formParams.containsModel = '';
        this.defaultModelKeys = [];
        break;
      case 2:
        this.supplierSelected = this.supplierOptions.map((item: any) => item.id);
        break;
    }
  }

  /**
   * 机型 | 货主 ** 全不选 **
   * @param type 1：机型 2：货主
   */
  modelOwnerNotAllChange(type: number) {
    switch (type) {
      case 1:
        this.modelAll = false;
        this.formParams.containsModel = '';
        this.defaultModelKeys = [];
        break;
      case 2:
        this.supplierAll = false;
        this.supplierSelected = [];
        break;
    }
  }

  // 货主 select change
  supplierChange(val: any) {
    if (!val.length || val.length !== this.supplierOptions.length) {
      this.supplierAll = false;
    } else if (val.length === this.supplierOptions.length) {
      this.supplierAll = true;
    }
  }


  /**
   * ----------------------------------------------------------------
   * Other
   * ----------------------------------------------------------------
   */
  dateChange(result: any[], keys: string[]) {
    this.formParams[keys[0]] = result.length ? this.datePipe.transform(result[0], 'yyyy-MM-dd HH:mm:ss') : '';
    this.formParams[keys[1]] = result.length ? this.datePipe.transform(result[1], 'yyyy-MM-dd HH:mm:ss') : '';
  }

  setDisabled(special?: string) {
    // str 'special'
    if (this.routeParams.id && ['2'].includes(this.routeParams.type)) {
      return true;
    }
    return false;
  }

  back() {
   history.back();
  }

  verifData() {
    if (this.commonService.isEmpty(this.formParams.name)) {
      this.message.warning('请输入标题');
      return false;
    } else if (this.commonService.isEmpty(this.formParams.status)) {
      this.message.warning('请选择状态');
      return false;
    } else if (this.commonService.isEmpty(this.formParams.img)) {
      this.message.warning('请上传水印图片');
      return false;
    } else if (!this.takeEffectDates.length) {
      this.message.warning('请选择生效时间');
      return false;
    } else if (this.commonService.isEmpty(this.formParams.userType)) {
      this.message.warning('请选择适用用户');
      return false;
    } else {
      return true;
    }
  }

  imageBeforeUpload = (file: any): Observable<boolean> =>
    new Observable((observer: Observer<boolean>) => {
      let isSquareImg = false;
      let isLt5M = false;

      let url = URL.createObjectURL(file);
      let image = new Image();
      image.src = url;
      image.onload = () => {
        isSquareImg = image.width === image.height;
        if (image.width !== image.height) {
          this.message.warning('请上传正方形图片!');
          observer.complete();
          return
        }

        isLt5M = file.size! / 1024 / 1024 < 5;
        if (!isLt5M) {
          this.message.warning('图像须小于5MB!');
          observer.complete();
          return;
        }

        observer.next(isSquareImg && isLt5M);
        observer.complete();
      }
    });

  /**
   * ----------------------------------------------------------------
   * submit form
   * ----------------------------------------------------------------
   */
  async submitData() {
    if (!this.verifData()) {
      return
    }

    let params: any = {
      ...this.formParams,
      containsModel: this.paramHandle(this.modelAll, this.formParams.containsModel), // 机型
      containsSupplier: (!this.supplierAll && !this.supplierSelected.length) ? '-1' : this.supplierSelected.join(','), // 货主
      isSup: this.supplierAll ? 0 : 1, // 0全选 1不全选(后端判断可用商品使用)
      containsColourB: this.selectConditionB.length === 0 ? -1 : this.selectConditionB.length === this.conditionOptionsB.length ? 0 : this.selectConditionB.join(','),
      containsColourC: this.selectConditionC.length === 0 ? -1 : this.selectConditionC.length === this.conditionOptionsC.length ? 0 : this.selectConditionC.join(','),
      filterGoods: this.excludeGoodsIds.length ? this.excludeGoodsIds.join(',') : '0', // 排除商品
      containsGoods: this.addGoodsIds.length ? this.addGoodsIds.join(',') : '0' // 追加商品
    }
    if (this.routeParams.id) {
      params.id = this.routeParams.id;
    }

    this.subformLoading = true;
    const {code, message}: any = await this.services.updateGoodsWaterData(params);
    this.subformLoading = false;

    if (code === 0) {
      this.message.success('操作成功');
      this.back();
    } else {
      this.message.error(message);
    }
  }

  /**
   * ----------------------------------------------------------------
   * 冲突验证 Modal
   * ----------------------------------------------------------------
   */
  async loadConflictData() {
    let params = {
      id: this.routeParams.id
    }
    this.conflictLoading = true;
    const {code, data, message}: any = await this.services.queryConflictData(params);
    this.conflictLoading = false;
    
    if (code === 0) {
      this.conflictTableData = [data.watermark, ...data.list];
    } else {
      this.message.error(message);
    }
  }

  showConflictModal() {
    this.loadConflictData();
    this.isConflictVisible = true;
  }
}
